package com.app.trafficclient.ShengHuoZhiShu;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.app.trafficclient.R;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LifeIndex extends AppCompatActivity {

    private ImageView imageViewBack;
    private TextView tvTitle;
    private TextView lifeTvDengJi1;
    private TextView lifeIndexTvTiShiYu1;
    private TextView lifeTvDengJi2;
    private TextView lifeIndexTvTiShiYu2;
    private TextView lifeTvDengJi3;
    private TextView lifeIndexTvTiShiYu3;
    private TextView lifeTvDengJi4;
    private TextView lifeIndexTvTiShiYu4;
    private TextView lifeTvDengJi5;
    private TextView lifeIndexTvTiShiYu5;
    TextView[] alldengJi=new TextView[5];
    TextView[] allTiShi = new TextView[5];
    Context context = LifeIndex.this;
    Boolean aBoolean = true;
    String url = "http://www.wpwh.info/environment/all-sensor";
    RequestQueue requestQueue ;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_life_index);
        initView();
        initHandler();
        initThread();
        getSensorData();
    }

    private void initThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (aBoolean) {
                    try {
                        Thread.sleep(3000);
//                        Message message = new Message();
//                        message.what = 1;
                        handler.sendEmptyMessage(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
//                Log.d("run!!hand运行了","!!!");
                getSensorData();
            }
        };
    }

    /**
 *发送网络请求得到传感器数值
 * */
    private void getSensorData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", "user1");
        JSONObject jsonObject = new JSONObject(map);
        final JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                         Log.d("run!!",response.toString());
                        String s = response.toString();
                        Gson gson =new Gson();
                        ZhiShuBean zhiShuBean =gson.fromJson(s,ZhiShuBean.class);
                        int guangZhao =zhiShuBean.getLight();
                        int wenDu = zhiShuBean.getTemperature();
                        int shiDu = zhiShuBean.getHumidity();
                        int co2 = zhiShuBean.getCo2();
                        int pm2 = zhiShuBean.getPm();

//                        1
                        if (guangZhao>0 && guangZhao < 1000 ){
                            lifeTvDengJi1.setText("弱("+String.valueOf(guangZhao)+")");
                            lifeIndexTvTiShiYu1.setText("辐射较弱，涂擦SPF12~15、PA+护肤品");
                        }else if(guangZhao>= 1000 && guangZhao<= 3000){
                            lifeTvDengJi1.setText("中等("+String.valueOf(guangZhao)+")");
                            lifeIndexTvTiShiYu1.setText("涂擦SPF大于15、PA+防晒护肤品");
                        }else {
                            lifeTvDengJi1.setText("强("+String.valueOf(guangZhao)+")");
                            lifeIndexTvTiShiYu1.setText("尽量减少外出，需要涂抹高倍数防晒霜");
                        }
//                        2
                  if (wenDu <8){
                            lifeTvDengJi2.setText("较易发（"+String.valueOf(zhiShuBean.getTemperature()+")"));
                            lifeIndexTvTiShiYu2.setText("温度低，风较大，较易发生感冒，注意防护");
                         }else {
                             lifeTvDengJi2.setText( "少发（"+String.valueOf( zhiShuBean.getTemperature()+")" ) );
                             lifeIndexTvTiShiYu2.setText("无明显降温，感冒机率较低");
                         }
//                         3
                         if (wenDu<12){
                            lifeTvDengJi3.setText("冷（"+String.valueOf(zhiShuBean.getTemperature())+"）");
                            lifeIndexTvTiShiYu3.setText("建议穿长袖衬衫、单裤等服装");
                         }else if (wenDu>=12 && wenDu <=21){
                             lifeTvDengJi3.setText("舒适（"+String.valueOf(zhiShuBean.getTemperature())+"）");
                             lifeIndexTvTiShiYu3.setText("建议穿短袖衬衫、单裤等服装");
                         }else if (wenDu>21){
                             lifeTvDengJi3.setText("热（"+String.valueOf(zhiShuBean.getTemperature())+"）");
                             lifeIndexTvTiShiYu3.setText("适合穿T恤、短薄外套等夏季服装");
                         }
//                         4
                         if(co2>0 && co2<3000){
                            lifeTvDengJi4.setText(    "适宜（" + String.valueOf(zhiShuBean.getCo2() ) + "）"    );
                            lifeIndexTvTiShiYu4.setText("气候适宜，推荐您进行户外运动");
                         }else if (co2>=3000 && co2<=6000){
                             lifeTvDengJi4.setText(     "中（"  + String.valueOf(zhiShuBean.getCo2())  + "）"     );
                             lifeIndexTvTiShiYu4.setText("易感人群应适当减少室外活动");
                         }else{
                             lifeTvDengJi4.setText("较不宜（"+String.valueOf(zhiShuBean.getCo2())+"）");
                             lifeIndexTvTiShiYu4.setText("空气氧气含量低，请在室内进行休闲运动");
                             }
//                             5

                         if (pm2>0 &&pm2<30){
                            lifeTvDengJi5.setText("优（"+String.valueOf(zhiShuBean.getPm())+"）");
                            lifeIndexTvTiShiYu5.setText("空气质量差，不适合户外活动");
                         }else if (pm2>=30 && pm2<=100){
                             lifeTvDengJi5.setText("良（"+String.valueOf(zhiShuBean.getPm())+"）");
                             lifeIndexTvTiShiYu5.setText("空气质量非常好，非常适合户外活动，趁机出去多呼吸新鲜空气");
                         }else {
                             lifeTvDengJi5.setText("污染（" + String.valueOf(zhiShuBean.getPm()) +  "）"   );
                             lifeIndexTvTiShiYu5.setText("空气质量差，不适合户外活动");
                         }
                         Toast.makeText(getApplicationContext(),"ok",Toast.LENGTH_SHORT).show();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                    Log.e("tag1", error.getMessage(), error);
            }
        });
        jsonRequest.setTag("tag");
        requestQueue.add(jsonRequest);

    }//

    @Override
    protected void onDestroy() {
       aBoolean = false;
       requestQueue.cancelAll("tag");
        super.onDestroy();
    }

    private void initView() {
        requestQueue = Volley.newRequestQueue(context);
        imageViewBack = findViewById(R.id.imageView_back);
        imageViewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("生活指数");
        lifeTvDengJi1 = findViewById(R.id.life_tv_dengJi1);
        lifeIndexTvTiShiYu1 = findViewById(R.id.life_index_tv_tiShiYu1);
        lifeTvDengJi2 = findViewById(R.id.life_tv_dengJi2);
        lifeIndexTvTiShiYu2 = findViewById(R.id.life_index_tv_tiShiYu2);
        lifeTvDengJi3 = findViewById(R.id.life_tv_dengJi3);
        lifeIndexTvTiShiYu3 = findViewById(R.id.life_index_tv_tiShiYu3);
        lifeTvDengJi4 = findViewById(R.id.life_tv_dengJi4);
        lifeIndexTvTiShiYu4 = findViewById(R.id.life_index_tv_tiShiYu4);
        lifeTvDengJi5 = findViewById(R.id.life_tv_dengJi5);
        lifeIndexTvTiShiYu5 = findViewById(R.id.life_index_tv_tiShiYu5);
    }
}
